package com.smzd.framework.config.handlers;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;

import com.smzd.framework.utils.JsonHelper;

public class AccessDeniedHandler extends AccessDeniedHandlerImpl {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
            AccessDeniedException accessDeniedException) throws IOException, ServletException {
        String method = request.getParameter("_method");
        boolean json = method != null && "json".equalsIgnoreCase(method);
        if (json) {
            String contentType = "application/json";
            response.setContentType(contentType);
            PrintWriter out = response.getWriter();
            out.print(JsonHelper.getFailJsonString(accessDeniedException == null ? "访问被拒绝！" : accessDeniedException
                    .getMessage()));
            out.flush();
            out.close();
        } else {
            super.handle(request, response, accessDeniedException);
        }

    }

}
